<template>
  <div class="a-header">
    <span class="title-name return-left" @click="toReturn(1)">
      <img src="../../assets/img/popup_icon_tuihui_defa.png" alt="" />返回
    </span>
  </div>
  <!-- route.query.type === 'pushMessage'  应用推送消息  不需要面包屑 权限按钮有所不同-->
  <div class="a-main">
    <div class="main-left">
      <div class="main-left-cont">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="详情">
            <div class="main-header">
              <a-button class="top-button" @click="toPrint">打印</a-button>
              <a-button
                class="top-button"
                style="margin-left: 8px"
                @click="toDownload('domRef', 'down')"
                >下载</a-button
              >
            </div>
            <!--startprint-->
            <div class="a-cont">
              <FormExamineComponent
                :form-fields="formFields"
                :text-type="textType"
              ></FormExamineComponent>
            </div>
            <!--endprint-->
          </a-tab-pane>
          <a-tab-pane v-if="editSeparately * 1 === 1" key="2" tab="正文" force-render>
            <div v-if="zhengwenOrUrl === 'zhengwen'" class="main-header">
              <template v-if="textType * 1 == 2">
                <template v-if="zhengWen">
                  <a-button class="top-button" @click="toPrintZhengwen()">打印</a-button>
                  <a-button class="top-button" style="margin-left: 8px" @click="toDownloadZhengwen">
                    下载
                  </a-button>
                </template>
              </template>
              <template v-else>
                <template v-if="zhengWen">
                  <a-button class="top-button" @click="toPrintZhengwen">打印</a-button>
                  <a-button class="top-button" style="margin-left: 8px" @click="toDownloadZhengwen">
                    下载
                  </a-button>
                </template>
              </template>
            </div>
            <div v-if="zhengwenOrUrl === 'url'" class="main-header">
              <template v-if="urls">
                <a-button class="top-button" @click="toPrintUrl(urls)">打印</a-button>
                <a-button class="top-button" style="margin-left: 8px">
                  <a :href="urls">下载</a>
                </a-button>
              </template>
            </div>
            <!-- 富文本 或者文本 -->
            <div
              v-if="zhengwenOrUrl === 'zhengwen'"
              id="detailsIds"
              ref="detailsIds"
              class="a-cont"
            >
              <div v-if="textType * 1 == 2">
                <template v-if="zhengWen">
                  <div class="text-title">{{ zhengWen.textTitle }}</div>
                  <div class="zhengwen-name">{{ zhengWen.text }}</div>
                </template>
                <div v-else class="no-datas">
                  <img src="../../assets/images/no-datas.png" alt="" />
                  <div class="tipss">未上传正文内容</div>
                </div>
              </div>
              <template v-else>
                <div v-if="zhengWen" v-html="zhengWen"></div>
                <div v-else class="no-datas">
                  <img src="../../assets/images/no-datas.png" alt="" />
                  <div class="tipss">未上传正文内容</div>
                </div>
              </template>
            </div>
            <!-- 正文地址 -->
            <div v-else class="a-conts">
              <iframe
                v-if="urls"
                :src="textUrl"
                loading="lazy"
                frameborder="0"
                width="100%"
                style="height: 1004px"
              ></iframe>
              <div v-else class="no-datas">
                <img src="../../assets/images/no-datas.png" alt="" />
                <div class="tipss">未上传正文内容</div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <div class="main-right">
      <div class="fubox-title">审批流程</div>
      <div class="fubox-box">
        <div v-for="(item, index) in systemUserDtos" :key="item.id" class="all-box">
          <div v-if="item.systemUser.length === 1" class="fubox-item">
            <div class="img">
              <img
                :src="item.systemUser[0].avatar ? item.systemUser[0].avatar : imgDefault"
                alt=""
                class="phopo"
              />
              <img
                :src="
                  finishState * 1 === 5 && item.status * 1 === 0
                    ? stateCode[9][0]
                    : stateCode[item.status][0]
                "
                alt=""
                class="stste-img"
              />
            </div>
            <div class="item-right">
              <div class="item-top">
                <div class="name"> {{ item.nodeName }} </div>
                <div class="time">{{ item.createTime }}</div>
              </div>
              <div class="item-name">
                {{ item.systemUser[0].username }}
                <span v-if="item.nodeType == 1"> (发起审批) </span>
                <span v-if="item.status == 0"> </span>
                <!-- <span v-if="item.status == 3">(已撤销) </span> -->
                <span v-if="item.status != 0 && item.nodeType != 1">
                  <span v-if="item.type == 7"> (退回)</span>
                  <span v-else-if="item.type == 6">
                    (加签)
                    <div>
                      添加审批人：{{ item.systemUser[0] ? item.systemUser[0].usernames : '' }}
                    </div>
                  </span>
                  <span v-else-if="item.nodeType == 3 && item.status == 1"> (已抄送)</span>
                  <span v-else-if="item.nodeType == 4 && item.status == 2"> (办理中) </span>
                  <span v-else> {{ '(' + statusObj[item.status] + ')' }}</span>
                </span>
              </div>
              <div v-if="item.reason" class="notes">
                {{ item.reason }}
              </div>
            </div>
            <div v-if="index !== systemUserDtos.length - 1" class="lines"></div>
          </div>
          <div v-else class="fubox-item">
            <div class="img">
              <img src="@/assets/img/oa_icon_quanburenyuan@2x.png" alt="" class="phopo" />
              <img
                :src="
                  finishState * 1 === 5 && item.status * 1 === 0
                    ? stateCode[9][0]
                    : stateCode[item.status][0]
                "
                alt=""
                class="stste-img"
              />
            </div>
            <div class="item-right" @click="downClick(item, downClickShow)">
              <div class="item-top">
                <div class="name"> {{ item.nodeName }} </div>
                <div class="time">{{ item.createTime }}</div>
              </div>
              <div class="item-names">
                <span>{{ item.systemUser.length }}人</span>
                <div>
                  <div v-if="item.checked" class="item-down">
                    <img src="@/assets/img/icon_select_up@2x.png" alt="" />
                  </div>
                  <div v-else class="item-down">
                    <img src="@/assets/img/icon_select_down@2x.png  " alt="" />
                  </div>
                </div>
              </div>
              <div v-if="item.checked" class="child-li">
                <div v-for="ite in item.systemUser" :key="ite.id" class="li">
                  <div class="people">
                    <div class="img-bg">
                      <img :src="ite.avatar ? ite.avatar : imgDefault" alt="" />
                    </div>
                    <div class="people-name">{{ ite.username }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="index !== systemUserDtos.length - 1" class="lines"></div>
          </div>
        </div>
      </div>
      <template v-if="route.query.type !== 'pushMessage'">
        <!-- 项目中的逻辑 -->
        <!-- 待归档 'toArchived' 已归档 archived ;  待归档的  办理中有催办;已归档的  啥状态都没有-->
        <div v-if="route.query.type === 'toArchived' && finishState * 1 === 2" class="bottom">
          <div class="btn-list">
            <!-- <a-button v-if="finishState * 1 === 2" @click="toDiscard">废弃</a-button> -->
            <a-button class="urging" type="primary" @click="toUrging">催办</a-button>
          </div>
        </div>
        <!-- 公文收发=>我登记的'my' 状态是2的 办理中才会又撤销与催办 -->
        <div v-if="route.query.type === 'my' && finishState * 1 === 2" class="bottom">
          <div class="btn-list">
            <a-button class="revoke revokes colors" @click="toRevoke">撤销</a-button>
            <a-button class="urging" type="primary" @click="toUrging">催办</a-button>
          </div>
        </div>
        <!-- 公文办理=>我得待办'needDealt' 与已办'completed'(已办只有处理中才会又催办) -->
        <div v-if="route.query.type === 'completed' && finishState * 1 === 2" class="bottom">
          <div class="btn-list">
            <a-button class="urging" type="primary" @click="toUrging">催办</a-button>
          </div>
        </div>
        <div v-if="route.query.type === 'needDealt' && finishState * 1 === 2" class="bottom">
          <!-- 固定审批 2 -->
          <div v-if="currentNodeType * 1 === 2" class="btn-list">
            <a-button @click="toTransfer">转办</a-button>
            <a-button class="revoke colors" @click="toPass(1)">拒绝</a-button>
            <a-button class="urging" type="primary" @click="toPass(2)">通过</a-button>
          </div>
          <!-- 固定办理 4-->
          <div v-if="currentNodeType * 1 === 4" class="btn-list">
            <a-button class="colors" @click="toTransfer">转办</a-button>
            <a-button class="urging" type="primary" @click="toPass(3)">提交</a-button>
          </div>
        </div>
      </template>
      <template v-if="route.query.type === 'pushMessage'">
        <!-- 消息推送按钮的逻辑 为了不影响之前的权限-->
        <div v-if="pushMessageState === 'shenpi'" class="bottom">
          <div class="btn-list">
            <a-button @click="toTransfer">转办</a-button>
            <a-button class="revoke colors" @click="toPass(1)">拒绝</a-button>
            <a-button class="urging" type="primary" @click="toPass(2)">通过</a-button>
          </div>
        </div>
        <div v-if="pushMessageState === 'banli'" class="bottom">
          <div class="btn-list">
            <a-button class="colors" @click="toTransfer">转办</a-button>
            <a-button class="urging" type="primary" @click="toPass(3)">提交</a-button>
          </div>
        </div>
        <div v-if="pushMessageState === 'faqiren'">
          <!-- 发起人没有按钮 暂时不知道啥情况先空这把 -->
        </div>
        <div v-if="pushMessageState === 'banliing'" class="bottom">
          <div class="btn-list">
            <a-button class="revoke colors revokes" @click="toRevoke">撤销</a-button>
            <a-button class="urging" type="primary" @click="toUrging">催办</a-button>
          </div>
        </div>
      </template>
    </div>
  </div>
  <div class="downs-box">
    <!-- 详情打印 -->
    <IndexPrint v-if="indexPrintShows" :text-type="textType" :table-data="tableData"></IndexPrint>
  </div>
  <div class="down-box">
    <Download
      v-if="downloadShows"
      id="download"
      ref="download"
      :text-type="textType"
      :table-data="tableData"
    ></Download>
  </div>
  <div class="down-box">
    <!-- 正文打印 -->
    <Downloadzhengwen
      v-if="downloadShowZhengwen"
      id="download"
      ref="download"
      :text-type="textType"
      :table-data="zhengWen"
    ></Downloadzhengwen>
  </div>
  <!-- 弹窗比较多 暂时都是复制出来的 后期处理组件吧 -->
  <!-- 返回弹窗 -->
  <a-modal
    v-model:visible="returnVisible"
    class="return-box"
    width="340px"
    :closable="false"
    :footer="null"
    @ok="handleOk"
    @cancel="cancel"
  >
    <div class="model-head">
      <div class="head-left">
        <img src="../../assets/img/xiangqing_icon_tixing@2x.png" alt="" />
        <div>提示</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="cancel" />
    </div>
    <div class="model-body"> 当前存在正文内容，切换模式会造成数据丢失，确定操作吗？ </div>
    <div class="btn-list">
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </div>
  </a-modal>
  <!-- 撤销弹窗 -->
  <a-modal
    v-model:visible="revokeVisible"
    class="return-box"
    width="480px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <div class="chexiao">{{ discardTitle }}</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="revokeCancel" />
    </div>
    <div class="model-body">
      <div class="body-head">
        <div class="tips">*</div>
        <div> {{ discardTitle }}原因 </div>
      </div>
      <a-textarea
        v-model:value="reasons"
        class="input-box"
        :maxlength="100"
        placeholder="请输入内容"
        :auto-size="{ minRows: 2, maxRows: 4 }"
      >
      </a-textarea
      ><span class="num"> {{ reasons.length }}/100</span>
    </div>
    <div class="btn-list">
      <a-button @click="revokeCancel">取消</a-button>
      <a-button type="primary" @click="revokeOk">确定</a-button>
    </div>
  </a-modal>
  <!-- 催办弹窗 -->
  <a-modal
    v-model:visible="urgingVisible"
    class="return-box"
    width="480px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <div class="chexiao">催办</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="urgingCancel" />
    </div>
    <div class="model-body body-bg">
      <a-checkbox
        v-model:checked="checkAll"
        :indeterminate="indeterminate"
        @change="onCheckAllChange"
      >
        全选
      </a-checkbox>
      <div class="phope-box">
        <div v-for="item in plainOptions" :key="item.id" class="phope-item">
          <a-checkbox v-model:checked="item.checked" @click="onChecked(item, $event)">
            <div class="checked-item">
              <div class="img-box">
                <img :src="item.avatar ? item.avatar : imgDefault" alt="" class="img" />
              </div>
              <span>{{ item.realName }}</span>
            </div>
          </a-checkbox>
        </div>
      </div>
    </div>
    <div class="btn-list">
      <a-button @click="urgingCancel">取消</a-button>
      <a-button type="primary" @click="urgingOk">确定</a-button>
    </div>
  </a-modal>
  <!-- 通过 拒绝弹窗 -->
  <a-modal
    v-model:visible="passVisible"
    class="return-box"
    width="472px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <div class="chexiao">{{ passTitle }}</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="passCancel" />
    </div>
    <div class="model-body">
      <div class="body-head">
        <div> 处理意见 </div>
      </div>
      <a-textarea
        v-model:value="passValue"
        class="input-box"
        placeholder="请输入内容"
        :maxlength="100"
        :auto-size="{ minRows: 2, maxRows: 4 }"
      >
      </a-textarea
      ><span class="num"> {{ passValue.length }}/100</span>
    </div>
    <div class="btn-list">
      <a-button @click="passCancel">取消</a-button>
      <a-button type="primary" @click="passOk">确定</a-button>
    </div>
  </a-modal>
  <!-- 转办弹窗 -->
  <a-modal
    v-model:visible="transferVisible"
    class="return-box"
    width="482px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <div class="chexiao">转办</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="transferCancel" />
    </div>
    <div class="model-body">
      <div class="zhuan-ban">
        <div class="top"><div class="tips">*</div> <div> 转办人 </div></div>

        <div class="add-list">
          <div class="all-people" :class="echoData.length === 0 ? 'no-marg' : null">
            <div
              v-if="maxCount <= 500"
              class="add"
              :class="echoData.length === 0 ? 'm-top' : null"
              @click="addPhopo"
            >
              <svg-icon icon-class="icon_upload_normal" class-name="icon-select-date"></svg-icon>
              <!-- <img src="../../assets/img/bianji_icon_tianjia_nor@2x.png" alt="" /> -->
            </div>
            <div v-if="echoData.length >= 1" class="add-img">
              <img src="../../assets/img/bianji_icon_tianjia_nor@2x.png" alt="" />
            </div>
          </div>

          <div v-for="(item, index) in echoData" :key="item.id" class="all-people">
            <div class="people-li">
              <img :src="item.icon ? item.icon : imgDefault" alt="" class="icos" />
              <img
                src="../../assets/img/icon_delete@2x.png"
                alt=""
                class="delete-img"
                @click="deletePeople(item.userId)"
              />
              <a-tooltip>
                <template v-if="item.userName.length > 6" #title>{{ item.userName }}</template>
                <div class="name">{{ item.userName }}</div>
              </a-tooltip>
            </div>
            <div v-if="index !== echoData.length - 1" class="add-img">
              <img src="../../assets/img/bianji_icon_tianjia_nor@2x.png" alt="" />
            </div>
          </div>
        </div>
      </div>

      <div class="body-head">
        <div> 处理意见 </div>
      </div>
      <div class="input-boxs">
        <a-textarea
          v-model:value="transferValue"
          class="input-box"
          placeholder="请输入内容"
          :maxlength="100"
          :auto-size="{ minRows: 2, maxRows: 4 }"
        >
        </a-textarea
        ><span class="nums"> {{ transferValue.length }}/100</span>
      </div>
    </div>
    <div class="btn-list">
      <a-button @click="transferCancel">取消</a-button>
      <a-button type="primary" @click="transferOk">确定</a-button>
    </div>
  </a-modal>
  <!-- 组织架构选择审批人弹框  ---转办 -->
  <MyPickProple
    v-if="showPupopStruct"
    v-model:visible="showPupopStruct"
    :max-count="maxCount"
    :appoint-state="appointState"
    :role-lists="roleList"
    :contacts-list="contactsList"
    :type="'people'"
    :echo-data="echoData"
    @onOK="updateMember"
  ></MyPickProple>
  <!-- 详情消息提醒 -->
  <a-modal
    v-model:visible="pushMessage"
    class="return-box"
    width="340px"
    :closable="false"
    :footer="null"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="cancel"
  >
    <div class="model-head">
      <div class="head-left">
        <img src="../../assets/img/xiangqing_icon_tixing@2x.png" alt="" />
        <div>温馨提示</div>
      </div>
      <!-- <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="cancel" /> -->
    </div>
    <div class="model-body"> {{ pushMessageValue }} </div>
    <div class="btn-list">
      <a-button type="primary" @click="pushMessageOk">确定</a-button>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, reactive, defineComponent, onMounted, watch, provide } from 'vue';
import html2canvas from 'html2canvas';
import { TjPickAndGroup } from 'tj-design-vue';
import JsPDF from 'jspdf';
import printJS from 'print-js';
import { message } from 'ant-design-vue';
import { useRoute, useRouter } from 'vue-router';
import LoadingImage from '@/components/loadingComponent/index.vue';
import {
  getDetail,
  hurryHandle,
  revokeTask,
  abandon,
  completeTask,
  userValidate,
  deleteTask,
  getDeptTree,
  getCurrentApproveUserList,
  transferTask,
  updateDocumentHandler,
  PdfConversion,
  getFrequentContacts,
  getRelationSchoolRoleStruct
} from '@/api/receiveDetails';
import IndexPrint from '@/views/library/download/indexPrint.vue';
import Download from '@/views/library/download/index.vue';
import Downloadzhengwen from '@/views/library/download/indexPrintZhengwen.vue';
import FormExamineComponent from '../../components/formExamineComponent/index.vue';
import store from '../../store';
import MyPickProple from '@/components/pickProple/index.vue';
const route = useRoute();
const router = useRouter();
const documentTitle = ref(route.query.documentTitle);
const flag = ref(true);
const uploading = ref(false);
const msg = ref();
let tableData = ref([]); // 下载模板数据
let downloadShows = ref(false); // 下载模板状态
const upFile = ref({});
let returnVisible = ref(false); // 返回提示窗状态
let downClickShow = ref(1); // 点击下拉人状态
function downClick(data, val) {
  if (val * 1 === 1) {
    downClickShow.value = 2;
    data.checked = true;
  } else {
    downClickShow.value = 1;
    data.checked = false;
  }
}
let pushMessage = ref(false); // 消息弹窗状态
let pushMessageValue = ref(''); // 消息弹窗提示语
function pushMessageOk() {
  pushMessage.value = false;
  toReturn();
}

const stateCode = ref({
  // 审批人状态
  0: [require('@/assets/img/icon_shenhe@2x.png'), '#F6A100', '未审核', 'color0'],
  1: [require('@/assets/img/icon_tongguo@2x.png'), '#1ABD15', '已通过', 'color1'],
  2: [require('@/assets/img/icon_shenhe@2x.png'), '#F6A100', '审核中', 'color2'],
  3: [require('@/assets/img/icon_jujue@2x.png'), '#FF3934', '已撤销 ', 'color3'],
  4: [require('@/assets/img/icon_jujue@2x.png'), '#FF3934', '已拒绝 ', 'color4'],
  5: [require('@/assets/img/icon_tongguo@2x.png'), '#1ABD15', '已转办', 'color1'],
  6: [require('@/assets/img/oa_icon_close@2x.png'), '#1ABD15', '已废弃', 'color1'],
  7: [require('@/assets/img/oa_icon_close@2x.png'), '#1ABD15', '已退回', 'color1'],
  8: [require('@/assets/img/oa_icon_jujue@2x.png'), '#1ABD15', '已通过', 'color1'],
  9: ['', '#1ABD15', '啥状态都不是 是X', 'color1']
});
let statusObj = ref({
  // 审批状态
  0: '未审核',
  1: '已通过',
  2: '审核中',
  3: '已撤销',
  4: '已拒绝',
  5: '已转办',
  6: '已加签',
  7: '已退回',
  8: '已废弃',
  null: ''
});
function getBread() {
  if (route.query.type === 'needDealt') {
    return '我的待办';
  } else if (route.query.type === 'completed') {
    return '我的已办';
  } else if (route.query.type === 'toArchived' || route.query.type === 'archiveded') {
    return '公文库';
  } else {
    return '收文登记';
  }
}
function toReturn(val) {
  // 公文办理=》 我得待办
  if (route.query.type === 'needDealt') {
    sessionStorage.setItem('tabsActive', '公文办理');
    sessionStorage.setItem('startingActives', '0');
  }
  // 公文办理=>我得已办
  if (route.query.type === 'completed') {
    sessionStorage.setItem('tabsActive', '公文办理');
    sessionStorage.setItem('startingActives', '1');
  }
  // 共文库=.待归档
  if (route.query.type === 'toArchived') {
    sessionStorage.setItem('tabsActive', '公文库');
    sessionStorage.setItem('startingActivesss', '0');
  }
  // 共文库=.已归档
  if (route.query.type === 'archiveded') {
    sessionStorage.setItem('tabsActive', '公文库');
    sessionStorage.setItem('startingActivesss', '1');
  }
  // 公文首发
  if (route.query.type === 'my') {
    sessionStorage.setItem('tabsActive', '公文收发');
    sessionStorage.setItem('startingActive', '1');
  }
  if (route.query.type === 'pushMessage') {
    sessionStorage.setItem('tabsActive', '公文办理');
    sessionStorage.setItem('startingActives', '0');
    router.push({
      path: '/index'
    });
  } else {
    router.push({
      path: '/index'
    });
  }
}
function cancel() {
  returnVisible.value = false;
}
function handleOk() {
  returnVisible.value = false;
}
const formFields = ref([]);
let download = ref(null);
const iValue = ref(30237);
onMounted(() => {
  getMouted();
});
let userTips = ref(''); // 用户校验提示语
function getMouted() {
  if (process.env.VUE_APP_WEB_URLS === 'dev' || process.env.VUE_APP_WEB_URLS === 'test') {
    iValue.value = 30237;
  }
  if (process.env.VUE_APP_WEB_URLS === 'preview') {
    iValue.value = 32109;
  }
  if (process.env.VUE_APP_WEB_URLS === 'pro') {
    iValue.value = 29781;
  }
  if (route.query.type === 'pushMessage') {
    activeKey.value = '1';
    userValidate({ processInstanceId: route.query.processInstanceId }).then(res => {
      console.log(res);
      if (res.code * 1 === 200) {
        userTips.value = res.data?.msg;
        setTimeout(() => {
          getInit();
        }, 100);
      }
    });
  } else {
    getInit();
  }
}
watch(route, (newValue, oldValue) => {
  if (newValue.query.type === 'pushMessage') {
    getMouted();
  }
});
let imgDefault = ref(require('@/assets/img/oa-img-default.png'));
let zhengWen = ref('');
let systemUserDtos = ref([]); // 审批流程数据
let finishState = ref(''); // 审批状态
let currentNodeType = ref(''); //
const taskId = ref(''); // 任务ID
const formId = ref(''); // 表单ID
const userId = ref(''); // 发起人id
let pushMessageState = ref(''); // 推送消息状态
let textType = ref(); // 区分pc h5 1=>h5 2=>pc
let textUrl = ref(''); // 正文 365地址
let urls = ref(''); // 完整正文地址
let textUrlConversion = ref(''); //  doc转pdf地址
let zhengwenOrUrl = ref(''); // 正文还是 富文本
let editSeparately = ref('');
// 获取详情
function getInit() {
  getDetail(route.query.processInstanceId).then(res => {
    if (res.code * 1 === 200) {
      let oaForm = res.data;
      if (oaForm.finish * 1 === 5 || oaForm.finish * 1 === 3 || oaForm.finish * 1 === 4) {
        oaForm.systemUserDtos = oaForm.systemUserDtos.filter(item => item.status * 1 !== 0);
        //  废弃状态
      }
      oaForm.contents.forEach(item => {
        if (item.componentName === 'TitleField') {
          documentTitle.value = item.content;
        }
      });
      finishState.value = oaForm.finish;
      currentNodeType.value = oaForm.currentNodeType;
      taskId.value = oaForm.taskId;
      formId.value = oaForm.oaForm.id;
      userId.value = oaForm.userId;
      editSeparately.value = res.data.oaForm.editSeparately;
      let data = oaForm.contents.filter(item => item.label);
      data = getAllData(data);
      formFields.value = data;
      let usertList = []; // 审批流程所有人
      oaForm.systemUserDtos.forEach(item => {
        item?.systemUser.forEach(it => {
          if (item.status * 1 !== 2 && item.status * 1 !== 0) {
            usertList.push({
              ...it,
              status: item.status,
              reason: item.reason,
              nodeId: item.nodeId,
              nodeType: item.nodeType,
              nodeName: item.nodeName,
              createTime: item.createTime,
              multiExamineType: item.multiExamineType
            });
          }
        });
      });
      // systemUserDtos.value = usertList; // 审批流程数据
      systemUserDtos.value = oaForm.systemUserDtos; // 审批流程数据
      textType.value = oaForm.textType;
      if (oaForm.textType * 1 === 1) {
        zhengwenOrUrl.value = oaForm.documentText ? 'zhengwen' : 'url';
        zhengWen.value = oaForm.documentText;
      } else {
        zhengwenOrUrl.value = oaForm.documentText ? 'zhengwen' : 'url';
        if (oaForm.documentText) {
          zhengWen.value = JSON.parse(oaForm.documentText);
        }
      }

      urls.value = oaForm.textUrl;
      textUrlConversion.value = oaForm?.textUrlConversion;
      textUrl.value = `https://ow365.cn/?i=${iValue.value}&ssl=1&pct=1&furl=` + oaForm.textUrl;
      console.log(textUrl.value, '????????');
      let flowList = [];
      usertList.forEach(item => {
        flowList.push({
          dataIndex: 'approval',
          title: item.nodeName,
          content: '',
          data: {
            status: item.status,
            nodeType: item.nodeType,
            nodeName: item.nodeName,
            name: item.username,
            time: item.createTime,
            notes: item.reason
          }
        });
      });
      let list = [];
      formFields.value.forEach(item => {
        list.push({
          attr: item.attr,
          type: item.componentName,
          title: item.label,
          content: item.content || ''
        });
      });
      tableData.value = [...list, ...flowList];
      console.log(tableData.value);
      if (route.query.type === 'pushMessage') {
        // 有taskId就是审批人 或者办理人; 没有就是发起人 通过是否是办理中判断是否有 撤销催办 按钮， 不是办理中的没有按钮
        // 消息推动进来的 要进行判断人的身份 （当前节点人的id===登陆人id 并且是审批中的状态  就是审批人； 不是审批中状态 就是发起人）
        let userInfo = JSON.parse(sessionStorage.getItem('USER_INFO'));
        console.log(555, userTips.value);
        if (
          oaForm.finish * 1 === 3 &&
          userTips.value === ' 该条公文已由发起人撤销，无需再进行办理'
        ) {
          pushMessageValue.value = '该条公文已由发起人撤销，无需再进行办理';
          pushMessage.value = true; // 消息弹窗状态
        }
        if (oaForm.finish * 1 === 5) {
          pushMessageValue.value = '该条公文已由管理员废弃，无需再进行办理';
          pushMessage.value = true; // 消息弹窗状态
        }

        // pushMessageValue.value = '该条公文已由其他或签人处理，无需再进行办理';

        if (oaForm.taskId) {
          if (oaForm.currentNodeType * 1 === 4) {
            // 固定办理
            pushMessageState.value = 'banli';
          }
          if (oaForm.currentNodeType * 1 === 2) {
            // 固定审批
            pushMessageState.value = 'shenpi';
          }
        } else {
          if (oaForm.userId === userInfo.businessId) {
            if (oaForm.finish * 1 === 2) {
              pushMessageState.value = 'banliing';
            } else {
              pushMessageState.value = 'faqiren';
            }
          }
        }
      }
    } else {
      formFields.value = [];
      systemUserDtos.value = [];
      if (route.query.type !== 'pushMessage') {
        message.warning(res.msg);
      }
    }
    if (route.query.type === 'pushMessage') {
      if (res.msg === '公文已被管理员删除') {
        pushMessage.value = true; // 消息弹窗状态
        pushMessageValue.value = '该条公文已被管理员删除';
      }
    }
  });
}
function getAllData(data) {
  data.forEach(item => {
    if (item.options) {
      let list = JSON.parse(item.options);
      if (item.componentName !== 'DDMultiSelectField') {
        list.forEach(it => {
          if (item.content === it.key) {
            item.content = it.value;
          }
        });
      }
    }
  });
  return data;
}
let activeKey = ref('1'); // tab 值
// 打印
let indexPrintShows = ref(false);
function toPrint() {
  indexPrintShows.value = true;
  setTimeout(() => {
    const printHTML = document.getElementById('domRef').innerHTML;
    console.log(printHTML);
    // 将打印的区域赋值，进行打印
    // console.log(window.document);
    window.document.body.innerHTML = printHTML;
    window.print(); // 调用window打印方法
    window.location.reload(); // 打印完成后重新加载页面
  });
  // router.push({
  //   path: '/library/print',
  //   query: {
  //     id: route.query.processInstanceId,
  //     token: sessionStorage.getItem('TOKEN')
  //   }
  // });
}
let downloadShowZhengwen = ref(false);
// 正文打印
function toPrintZhengwen() {
  console.log('打印正文');
  downloadShowZhengwen.value = true;
  toDownload('domRefs', 'print');
}
// 正文下载
function toDownloadZhengwen() {
  store.commit('user/isLoading', true);
  // downloadShows.value = true;
  // 调用htmlToPdf工具函数
  setTimeout(() => {
    getPdf('detailsIds', documentTitle.value);
  });
}
// 下载
function toDownload(dom, type) {
  if (type === 'down') {
    console.log(process.env.VUE_APP_WEB_URL.slice(0, process.env.VUE_APP_WEB_URL.length - 7));
    let url =
      process.env.VUE_APP_WEB_URL.slice(0, process.env.VUE_APP_WEB_URL.length - 7) +
      'document-circulation-v2/pc/#/library/onlyDownload?id=' +
      route.query.processInstanceId +
      '&token=' +
      sessionStorage.getItem('TOKEN');
    console.log(222, url);
    PdfConversion({ format: 'A4', url: url }).then(res => {
      console.log(res);
      if (res.code === 200) {
        downloadURL(res.data, documentTitle.value);
        // window.location.href = res.data;
      } else {
        message.error('下载文件失败！');
      }
    });
    // router.push({
    //   path: '/library/print',
    //   query: {
    //     id: route.query.processInstanceId,
    //     token: sessionStorage.getItem('TOKEN')
    //   }
    // });
  } else {
    console.log(dom, type);
    store.commit('user/isLoading', true);
    downloadShows.value = true;
    // // 调用htmlToPdf工具函数
    setTimeout(() => {
      getPdf(dom, documentTitle.value, type);
    }, 10);
  }
}
// 下载URL并重命名
function downloadURL(urls, name) {
  const download = new XMLHttpRequest();
  download.open('GET', urls, true);
  download.responseType = 'blob';
  download.onload = function () {
    const url = window.URL.createObjectURL(download.response);
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    a.click();
  };
  download.send();
}
function getPdf(domId, title, type) {
  console.log(domId);
  // title=>名字,type=》下载还是 打印
  let pdfDom = domId;
  // myLoading 自定义等待动画组件，实现导出事件的异步等待交互 dom的id。
  let target = document.getElementById(pdfDom);
  console.log(target);
  pdf(pdfDom, title, type);
}
const pdf = (pdfDom, title, type) => {
  // 避免出现浏览器滚动条导致的内容不全处理
  document.body.scrollTop = document.documentElement.scrollTop = 0;
  // div内部滚动导致内容不全处理
  html2canvas(document.getElementById(pdfDom), {
    allowTaint: true,
    useCORS: true,
    scale: 3, // 按比例增加分辨率
    dpi: 300 // 分辨率
    // height: document.getElementById(pdfDom).scrollHeight,
    // windowHeight: document.getElementById(pdfDom).scrollHeight
  }).then(canvas => {
    store.commit('user/isLoading', false);
    downloadShows.value = false;
    downloadShowZhengwen.value = false;
    let contentWidth = canvas.width;
    let contentHeight = canvas.height;
    // 一页pdf显示html页面生成的canvas高度;
    let pageHeight = (contentWidth / 592.28) * 841.89;
    // 未生成pdf的html页面高度
    let leftHeight = contentHeight;
    // 页面偏移
    let position = 0;
    // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
    let imgWidth = 595.28;
    let imgHeight = (592.28 / contentWidth) * contentHeight;
    let pageData = canvas.toDataURL('image/jpeg', 1.0);
    let pdf = new JsPDF('', 'pt', 'a4');
    // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
    // 当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        // 避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    if (type === 'print') {
      printJS({
        printable: pageData,
        type: 'image',
        base64: true,
        // documentTitle: '\u200E',
        style: `@media print { @page {size: auto; margin: 0; } body{margin:0 5px}}`
      });
    } else {
      pdf.save(`${title}.pdf`);
    }
  });
};
// 正文图片打印
function toPrintUrl(url) {
  console.log(url);
  if (url[url.length - 1] === 'g') {
    printJS({
      printable: url,
      type: 'image',
      base64: true,
      documentTitle: '\u200E',
      style: `@media print { @page {size: auto; margin: 0; } body{margin:0 5px}}`
    });
  } else {
    console.log(url, 'pad打印');
    let fileType = url.substr(-4);
    if (fileType === '.ofd' || fileType === '.OFD') {
      message.warning('当前文件格式为.ofd格式，暂不支持在线打印，请下载到本地打印。');
      return;
    } else {
      if (url.includes('.pdf')) {
        console.log('pdf', url);
        window.microappSDK.print(url);
      } else {
        console.log('word', textUrlConversion.value);
        window.microappSDK.print(textUrlConversion.value);
      }
    }

    // console.log(textUrlConversion.value, 90909);
    // printJS({
    //   printable: textUrlConversion.value.split(','),
    //   type: 'image',
    //   base64: true,
    //   documentTitle: '\u200E',
    //   style: `@media print { @page {size: auto; margin: 0; } body{margin:0 5px}}`
    // });
  }
}
// 撤销
let reasons = ref(''); // 撤销理由
let revokeVisible = ref(false); // 撤销弹窗状态
let discard = ref(''); // 撤销或者是废弃
let discardTitle = ref(''); // 废弃 撤销标题
// 废弃撤销公用
function toDiscard() {
  discardTitle.value = '废弃';
  revokeVisible.value = true;
  discard.value = 'feiqi';
}
// 撤销
function toRevoke() {
  discardTitle.value = '撤销';
  discard.value = 'chexiao';
  revokeVisible.value = true;
}
function revokeCancel() {
  revokeVisible.value = false;
  reasons.value = '';
}
function revokeOk() {
  if (!reasons.value) {
    if (discard.value === 'chexiao') {
      return message.warning('请填写撤销原因');
    }
    if (discard.value === 'feiqi') {
      return message.warning('请填写废弃原因');
    }
  }
  if (discard.value === 'chexiao') {
    // 撤销
    getRevokeTask();
  } else {
    // 废弃
    toaBandon();
  }
}
function getRevokeTask() {
  let params = {
    reason: reasons.value,
    processInstanceId: route.query.processInstanceId
  };
  revokeTask(params).then(res => {
    if (res.code * 1 === 200) {
      message.success(`撤销成功`);
      revokeVisible.value = false;
      reasons.value = '';
      toReturn(); // 回首页
    } else {
      message.error(res.msg);
    }
  });
}
function toaBandon() {
  let params = {
    abandonIdea: reasons.value,
    id: route.query.ids,
    processStatus: '5'
  };
  abandon(params).then(res => {
    if (res.code * 1 === 200) {
      message.success(`废弃成功`);
      revokeVisible.value = false;
      reasons.value = '';
      toReturn();
    } else {
      message.error(res.msg);
    }
  });
}
// 催办
let urgingVisible = ref(false); // 催办弹唱状态
function toUrging() {
  getCurrentApproveUserList(route.query.processInstanceId).then(res => {
    // 流程id
    plainOptions.value = res.data;
  });
  urgingVisible.value = true;
}
// 弹唱关闭
function urgingCancel() {
  urgingVisible.value = false;
  getCloseCuiban();
}
// 清除催办人
function getCloseCuiban() {
  plainOptions.value.forEach(item => {
    item.checked = false;
  });
  indeterminate.value = false;
  checkAll.value = false;
}
// 弹窗ok
function urgingOk() {
  let userIds = [];
  plainOptions.value.forEach(item => {
    if (item.checked) userIds.push(item.id);
  });
  if (userIds.length === 0) {
    message.warning('请选择催办人');
    return;
  }
  hurryHandle({
    userIds: userIds,
    processInstanceId: route.query.processInstanceId
  }).then(res => {
    if (res.code * 1 === 200) {
      message.success(`催办成功`);
      urgingVisible.value = false;
      getCloseCuiban();
      getInit();
    } else {
      message.error(res.msg);
    }
  });
}
function updateList() {
  updateDocumentHandler({
    processInstanceId: route.query.processInstanceId,
    formId: formId.value
  }).then(res => {
    console.log('新的接口', res);
  });
}
// 通过弹窗 相关
let passTitle = ref('');
let passVisible = ref(false);
let passValue = ref(''); // 通过备注
function passCancel() {
  passVisible.value = false;
  passValue.value = '';
}
function passOk() {
  passVisible.value = false;
  let params = {
    taskId: taskId.value, // 任务ID
    formId: formId.value, // 表单ID
    processInstanceId: route.query.processInstanceId, // 流程实例ID
    files: [], // 附件
    reason: passValue.value // 原因
  };

  if (passOrNo.value * 1 === 1) {
    funNoPass(params); // 拒绝
  } else {
    funPass(params); // 通过  提交
  }
  passValue.value = '';
}
function funPass(params) {
  completeTask(params)
    .then(res => {
      message.success(res.msg);
      updateList();
      toReturn(); // 返回
    })
    .catch(err => {
      message.error(err.data.msg);
    });
}
function funNoPass(params) {
  deleteTask(params)
    .then(res => {
      message.success(res.msg);
      updateList();
      toReturn(); // 返回
    })
    .catch(err => {
      message.error(err.data.msg);
    });
}
let maxCount = ref(500); // 选择最多人
const appointState = ref(false); // 是否是指定人员状态
const contactsList = ref([]); // 常用联系人
const roleList = ref([]); // 角色数组
let showPupopStruct = ref(false); // 选人弹窗状态
const pickData = ref([]); // 选人组件数据
const echoData = ref([]); // 回显数据/ 选中的转办人
// 转办选人
async function addPhopo() {
  // getDeptTree({}).then(res => {
  //   if (res.code * 1 === 200) {
  //     let _data = [
  //       {
  //         tabName: '组织架构',
  //         tabId: '2',
  //         itSecondaryMenu: false,
  //         childList: res.data
  //       }
  //     ];
  //     showPupopStruct.value = true;
  //     pickData.value = _data;
  //     // echoData.value = scope; // 回显数据
  //   }
  // });
  // 角色接口
  await getRelationSchoolRoleStruct({}).then(res => {
    if (res.code * 1 === 200) {
      let data = res.data;
      console.log('角色接口', data);
      roleList.value = data;
      store.commit('user/roleList', data); // 指定人员固定架构
    }
  });
  // 常用联系人
  await getFrequentContacts({}).then(res => {
    if (res.code * 1 === 200) {
      res.data.forEach(item => {
        item.userId = item.contactsUserId;
      });
      contactsList.value = res.data;
      provide('contactsListq', contactsList.value);
      store.commit('user/contactsList', contactsList.value);
    }
  });
  // 组织结构接口
  await getDeptTree({}).then(res => {
    if (res.code * 1 === 200) {
      let allPeoples = []; // 所有人
      let peopleLists = []; // 所有人
      res.data.forEach(item => {
        item.listPeople.forEach(it => {
          peopleLists.push({ ...it });
        });
      });
      allPeoples = peopleLists;
      let allPeople = allPeoples.reduce((acc, curr) => {
        let existingItem = acc.find(item => item.userId === curr.userId);
        if (existingItem) {
          existingItem.deptName += `，${curr.deptName}`;
        } else {
          acc.push({ ...curr });
        }
        return acc;
      }, []);
      allPeople.forEach(item => {
        item.username = item.userName;
      });
      // console.log(allPeople, '所有人');
      res.data.forEach(item => {
        item.categoryId = item.schoolBusinessId;
      });
      console.log(res.data, '组织结构数据');
      store.commit('user/departmentDatas', res.data);
      store.commit('user/allPeoples', allPeople);
      showPupopStruct.value = true; // 打开选人弹窗
    }
  });
}
// 移除人
function deletePeople(id) {
  echoData.value = echoData.value.filter(item => item.userId !== id);
}
// 选人确定
function updateMember(val) {
  val.forEach(item => {
    item.icon = item.avatar;
  });
  echoData.value = val;
}
// 转办弹窗相关
let transferVisible = ref(false);
let transferValue = ref(''); // 转办备注
// 转办弹窗
function transferCancel() {
  transferVisible.value = false;
  echoData.value = [];
  transferValue.value = '';
}
function transferOk() {
  if (echoData.value.length === 0) {
    message.warning('请选择转办人');
    return;
  }
  let id = [];
  echoData.value.forEach(item => {
    id.push(item.userId);
  });
  let params = {
    taskId: taskId.value, // 任务ID
    formId: formId.value, // 表单ID
    processInstanceId: route.query.processInstanceId, // 流程实例ID
    files: [], // 附件
    transferToUserIds: id, // 转交人ID
    initiatorUserId: userId.value, // 发起人ID
    reason: transferValue.value // 原因
  };
  transferTask(params).then(res => {
    console.log(333, res);
    if (res.code * 1 === 200) {
      message.success('转办成功');
      transferVisible.value = false;
      updateList();
      toReturn();
    } else {
      message.error(res.msg);
    }
  });
  transferValue.value = '';
}
let indeterminate = ref(false); // 办全选状态
let checkedList = ref([]); // 催办人绑定值
let plainOptions = ref([]); // 所有催办人
let checkAll = ref(false); // 全选状态
function onCheckAllChange() {
  if (checkAll.value) {
    indeterminate.value = false;
  } else {
    indeterminate.value = checkAll.value;
  }
  plainOptions.value.forEach(item => {
    item.checked = checkAll.value;
  });
}
function onChecked(data, e) {
  data.checked = e.target.checked;
  let list = [];
  plainOptions.value.forEach(item => {
    if (item.checked) list.push(item.checked);
  });
  if (list.length === plainOptions.value.length) {
    checkAll.value = true;
    indeterminate.value = false;
  } else {
    checkAll.value = false;
    if (list.length !== 0) {
      indeterminate.value = true;
    }
    if (list.length === 0) {
      checkAll.value = false;
      indeterminate.value = false;
    }
  }
}
// 转办
function toTransfer() {
  const firstElementWithIdTwo = systemUserDtos.value.find(element => element.status === 2); // 获取第一个状态等于2的 就是当前节点
  let list = []; // 已经转办人的人数集合
  systemUserDtos.value.forEach(item => {
    if (item.nodeId * 1 === firstElementWithIdTwo.nodeId * 1 && item.status === 5) {
      list.push(item.systemUser.length);
    }
  });
  maxCount.value = 500 - list.length;
  transferVisible.value = true;
}
// 通过
let passOrNo = ref(''); // 通过还是拒绝
function toPass(val) {
  passOrNo.value = val;
  if (val * 1 === 2) {
    passTitle.value = '通过';
  } else if (val * 1 === 3) {
    passTitle.value = '提交';
  } else {
    passTitle.value = '拒绝';
  }
  passVisible.value = true;
}
let color = ref(store.state.user.setPrimaryColor);
</script>

<style scoped lang="less">
@import './index.less';
.gutter-box {
  background: #00a0e9;
}
.ant-form-item-label {
  color: black;
}
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
  float: right;
}
.top-button {
  border-radius: 4px;
}
:deep.ant-tabs > .ant-tabs-nav {
  margin-left: 20px;
}
.bottom {
  position: absolute;
  bottom: 0;
  width: 335px;
  height: 56px;
  background: #ffffff;
  border-radius: 0px 0px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .btn-list {
    margin-right: 24px;
    :deep(.ant-btn) {
      padding: 4px 13px;
      margin-left: 16px;
      border: 1px solid rgba(186, 191, 197, 0.4) !important;
      height: 32px !important;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400 !important;
      font-family: Source Han Sans CN, Source Han Sans CN-Regular;
      color: rgba(0, 0, 0, 0.6) !important;
    }

    /deep/ .ant-btn:hover {
      color: v-bind('color') !important;
    }
    .colors:hover {
      color: v-bind('color') !important;
      border: 1px solid v-bind('color') !important;
    }
    .revokes:hover {
      color: red !important;
      border: 1px solid red !important;
    }
    :deep(.ant-btn-primary) {
      background: v-bind('color') !important;
      color: white !important;
      &:hover {
        color: white !important;
        border: 1px solid v-bind('color') !important;
      }
    }
  }
}
.fubox-box {
  height: calc(100vh - 208px);
  overflow-y: auto;
  padding-top: 20px;
  padding-bottom: 20px;
  &::-webkit-scrollbar {
    width: 4px !important;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(20, 20, 20, 0.2);
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
}
.ant-modal-content {
  border-radius: 6px !important;
}
.icon-select-date {
  color: v-bind('color');
  width: 18px !important;
  height: 18px !important;
}
.tianjian {
  z-index: 2030 !important;
}
/deep/ .tj-pick-mask {
  z-index: 2030 !important;
}
.text-title {
  text-align: center;
  margin-bottom: 16px;
}
.down-box {
  height: 1px !important;
  overflow: auto;
}
.lines {
  position: absolute;
  width: 2px;
  border-left: 2px solid #eff0f1;
  top: 55px;
  left: 45px;
  bottom: -49px;
  background-color: #eff0f1;
}
.bottom .btn-list[data-v-4d86a12e] .revoke:hover {
  color: red !important;
  border: 1px solid red !important;
}
.bottom .btn-list[data-v-4d86a12e] .urging:hover {
  color: white !important;
  background: let(--ant-primary-3) !important;
  border: 1px solid let(--ant-primary-3) !important;
}
.zhengwen-name {
  word-wrap: break-word;
  white-space: pre-line;
  overflow-wrap: break-word;
}
// .revoke:hover {
//   color: red !important;
//   border: 1px solid red !important;
// }
</style>
